package com.team.ai.service;

import com.team.ai.tool.Baidu.Current.FileUtil;
import com.team.ai.tool.Baidu.Current.GsonUtils;
import com.team.ai.tool.Baidu.Current.HttpUtil;
import com.team.ai.tool.Baidu.Current.OCRAuthService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 人脸融合
 */
@Component
public class FaceMergeService {
    @Resource
    OCRAuthService ocrAuthService;//OCR令牌
    public  String faceMerge(String filePath,String filePath1) {

        byte[] bytes1 = new byte[0];
        try {
            bytes1 = FileUtil.readFileByBytes(filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes2 = new byte[0];
        try {
            bytes2 = FileUtil.readFileByBytes(filePath1);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        String image1 = new BASE64Encoder().encode((bytes1));
//        String image2 = new BASE64Encoder().encode((bytes2));
        String encodeValue1 = Base64Utils.encodeToString(bytes1);
        String encodeValue2 = Base64Utils.encodeToString(bytes2);
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v1/merge";
        try {
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> image_templateMap = new HashMap<>();
            image_templateMap.put("image", encodeValue1);
            image_templateMap.put("image_type", "BASE64");
            image_templateMap.put("quality_control", "NONE");
            map.put("image_template", image_templateMap);
            Map<String, Object> image_targetMap = new HashMap<>();
            image_targetMap.put("image", encodeValue2);
            image_targetMap.put("image_type", "BASE64");
            image_targetMap.put("quality_control", "NONE");
            map.put("image_target", image_targetMap);
            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = ocrAuthService.getAuth(17);

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
